﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using EFong.Contract;
using EFong.ServicesInterface;
using EFong.BL;

namespace EFong.Services
{
    internal static class ServiceHelper
    {
        public static ServiceResult<T> Return<T>(this IService service, T returnValue)
        {
            ServiceResult<T> serviceResult = new ServiceResult<T>();
            serviceResult.IsSuccess = true;
            serviceResult.ReturnValue = returnValue;

            return serviceResult;
        }

        public static ServiceResult Return(this IService service)
        {
            ServiceResult serviceResult = new ServiceResult();
            serviceResult.IsSuccess = true;

            return serviceResult;
        }

        public static ServiceResult<T> Fail<T>(this IService service, BusinessException be)
        {
            ServiceResult<T> serviceResult = new ServiceResult<T>();
            serviceResult.IsSuccess = false;
            serviceResult.FailType = be.Type;
            serviceResult.FailMessage = be.Message;
            serviceResult.FailValues = be.FailValues;

            return serviceResult;
        }

        public static ServiceResult Fail(this IService service, BusinessException be)
        {
            ServiceResult serviceResult = new ServiceResult();
            serviceResult.IsSuccess = false;
            serviceResult.FailType = be.Type;
            serviceResult.FailMessage = be.Message;
            serviceResult.FailValues = be.FailValues;

            return serviceResult;
        }

        public static ServiceResult<T> Fail<T>(this IService service, Exception e)
        {
            ServiceResult<T> serviceResult = new ServiceResult<T>();
            serviceResult.IsSuccess = false;
            serviceResult.FailType = -1;
            StringBuilder messageBuilder = new StringBuilder();
            while(e != null)
            {
                messageBuilder.AppendLine(e.Message);
                e = e.InnerException;
            }
            serviceResult.FailMessage = messageBuilder.ToString();

            return serviceResult;
        }

        public static ServiceResult Fail(this IService service, Exception e)
        {
            ServiceResult serviceResult = new ServiceResult();
            serviceResult.IsSuccess = false;
            serviceResult.FailType = -1;
            StringBuilder messageBuilder = new StringBuilder();
            while (e != null)
            {
                messageBuilder.AppendLine(e.Message);
                e = e.InnerException;
            }
            serviceResult.FailMessage = messageBuilder.ToString();

            return serviceResult;
        }
    }
}
